package cn.android666.net.util.download.dialog

import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import android.text.format.Formatter
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import cn.android666.net.util.databinding.DialogDownloadingApkBinding

class DownloadDialog(
    private val appName: String,
    private val isForceUpdate: Boolean,
    private val pauseButtonOnClickListener: View.OnClickListener,
    private val cancelButtonOnClickListener: View.OnClickListener,
) : DialogFragment() {

    private var fileSize: String? = null
    private lateinit var binding: DialogDownloadingApkBinding
    private var max = -1L
    private var init = false

    @SuppressLint("SetTextI18n")
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        isCancelable = false

        binding = DialogDownloadingApkBinding.inflate(LayoutInflater.from(context), null, false)
        binding.tvTitle.text = "正在下载$appName"
        binding.tvProgress.text = "0KB/0MB"
        binding.tvDownloadSpeed.text = "0k/s"
        binding.viewPlaceholder.visibility = if (isForceUpdate) View.VISIBLE else View.GONE
        binding.llButton.visibility = if (isForceUpdate) View.GONE else View.VISIBLE
        binding.btnPause.setOnClickListener(pauseButtonOnClickListener)
        binding.btnCancel.setOnClickListener(cancelButtonOnClickListener)

        val dialog = AlertDialog.Builder(requireContext()).setView(binding.root).create()

        if (max > 0) {
            binding.pbProgress.max = max.toInt()
            fileSize = Formatter.formatFileSize(context, max)
            binding.tvProgress.text = "0KB/${fileSize}"
        }

        init = true
        return dialog
    }

    fun setButtonText(text: CharSequence) {
        // 这是点击对话框按钮后才设置的，所以不需要判断初始化，因为能点击按钮，说明对话框已经显示了
        binding.btnPause.text = text
    }

    @SuppressLint("SetTextI18n")
    fun setMax(max: Long) {
        if (init) {
            binding.pbProgress.max = max.toInt()
            fileSize = Formatter.formatFileSize(context, max)
            binding.tvProgress.text = "0KB/${fileSize}"
        } else {
            // 如果还没初始化，则先把设置保存，等到初始化完再设置
            this.max = max
        }
    }

    @SuppressLint("SetTextI18n")
    fun setProgress(progress: Long, speed: Long) {
        if (init) {
            binding.pbProgress.progress = progress.toInt()
            binding.tvProgress.text = "${Formatter.formatFileSize(context, progress)}/${fileSize}"
            binding.tvDownloadSpeed.text = "${Formatter.formatFileSize(context, speed)}/s"
        }
    }

}